package com.ugoodtech.mdcc.client.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.StationReportService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StationReportServiceImpl implements StationReportService {

    private final static Logger logger = LoggerFactory.getLogger(StationReportServiceImpl.class);

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private StationReportUnFinshedRepository stationReportUnFinshedRepository;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private StationColorReportTempRepository stationColorReportTempRepository;

    @Autowired
    private StationRegularServiceReportUnFinshedRepository stationRegularServiceReportUnFinshedRepository;

    @Autowired
    private ServiceReportRecorderRepository serviceReportRecorderRepository;

    @Autowired
    private ServiceReportHistoricalRecorderRepository serviceReportHistoricalRecorderRepository;

    @Autowired
    private ReportRedDotRepository reportRedDotRepository;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    private AuditReportRepository auditReportRepository;

    @Autowired
    private AuditColorReportRepository auditColorReportRepository;

    @Override
    public JsonResponse withdraw_deleteReport(User user, String reportType, String operation, Long reportId) {
        AuditReport auditReport = null;
        StationReport stationReport = null;
        if (reportType.equals(Constants.TECHCOLOR_REPORT)) {
            auditReport = auditReportRepository.findOne(reportId);
            if (!auditReport.getUser().getId().equals(user.getId())) {
                return JsonResponse.errorResponseWithError("抱歉", "只能撤回或删除自己的报告");
            }
        } else {
            // 若已经填写满意度报告则不能撤回
            stationReport = stationReportRepository.findOne(reportId);
            CustomerRegularReport customerRegularReport = customerRegularReportRepository.findByRegularReportIdNoCheckEnable(reportId);
            if (customerRegularReport.isType()){
                return JsonResponse.errorResponseWithError("抱歉", "不能撤回或删除已填写满意度报告的常规报告");
            }
            if (!stationReport.getUser().getId().equals(user.getId())) {
                return JsonResponse.errorResponseWithError("抱歉", "只能撤回或删除自己的报告");
            }
        }

        if (operation.equals(Constants.WITHDRAW_REPORT)) {
            logger.info("撤回报告");
            return withdrawReport(user, reportType, stationReport, auditReport);
        } else if (operation.equals(Constants.DELETE_REPORT)) {
            return deleteReport(user, reportType, stationReport, auditReport);
        }
        return JsonResponse.errorResponseWithError("抱歉", "操作失败");
    }

    /**
     * 撤回报告
     */
    private JsonResponse withdrawReport(User user, String reportType, StationReport stationReport, AuditReport auditReport) {
        if (reportType.equals(Constants.TECHCOLOR_REPORT)) {
            if (!auditReport.getAuditing().equals(Constants.AUDIT_APPLY)) {
                return JsonResponse.errorResponseWithError("抱歉", "只能撤回待审核的基础报告");
            } else {
                return withdrawColorReport(user, auditReport);
            }
        }
        if (reportType.equals(Constants.SERVICE_REPORT)) {
            if (!stationReport.getCategory().equals(Constants.SERVICE_REPORT)) {
                return JsonResponse.errorResponseWithError("抱歉", "此报告不是常规服务报告");
            } else {
                logger.info("撤回常规报告");
                return withdrawServiceReport(user, stationReport);
            }
        }
        return JsonResponse.errorResponseWithError("抱歉", "撤回失败");
    }

    /**
     * 删除报告
     */
    private JsonResponse deleteReport(User user, String reportType, StationReport stationReport, AuditReport auditReport) {
        if (reportType.equals(Constants.TECHCOLOR_REPORT)) {
            if (!auditReport.getAuditing().equals(Constants.AUDIT_APPLY)) {
                return JsonResponse.errorResponseWithError("抱歉", "只能删除待审核的基础报告");
            } else {
                return deleteColorReport(auditReport);
            }
        }
        if (reportType.equals(Constants.SERVICE_REPORT)) {
            if (!stationReport.getCategory().equals(Constants.SERVICE_REPORT)) {
                return JsonResponse.errorResponseWithError("抱歉", "此报告不是常规服务报告");
            } else {
                return deleteServiceReport(stationReport);
            }
        }
        return JsonResponse.errorResponseWithError("抱歉", "删除失败");
    }

    /**
     * 撤回基础报告
     */
    private JsonResponse withdrawColorReport(User user, AuditReport auditReport) {
        StationReportTemp stationReportTemp = new StationReportTemp();
        if (auditReport.getStation() != null) {
            stationReportTemp.setStation(auditReport.getStation());
        }
        stationReportTemp.setReportCategory(Constants.TECHCOLOR_REPORT);
        stationReportTemp.setUser(user);
        stationReportTemp.setUserType(auditReport.getUserType());
        stationReportTemp.setReportType(Constants.REPORT_TYPE_UNFINSHED);
        stationReportUnFinshedRepository.save(stationReportTemp);
        QAuditColorReport qStationColorReport = QAuditColorReport.auditColorReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationColorReport.deleted.eq(false));
        builder.and(qStationColorReport.enabled.eq(true));
        builder.and(qStationColorReport.auditReport.id.eq(auditReport.getId()));
        List<AuditColorReport> colorReportList = (List<AuditColorReport>) auditColorReportRepository.findAll(builder);

        for (AuditColorReport colorReport : colorReportList) {
            StationColorReportTemp colorReportTemp = new StationColorReportTemp();
            colorReportTemp.setStationReportUnFinshed(stationReportTemp);
            if (StringUtils.isNotEmpty(colorReport.getAnswerOther())) {
                colorReportTemp.setAnswerOther(colorReport.getAnswerOther());
            }
            if (StringUtils.isNotEmpty(colorReport.getAnswerId())) {
                colorReportTemp.setAnswerId(colorReport.getAnswerId());
            }
            if (StringUtils.isNotEmpty(colorReport.getAnswerPhoto())) {
                colorReportTemp.setAnswerPhoto(colorReport.getAnswerPhoto());
            }
            if (colorReport.getQuestionId() != null && colorReport.getQuestionId() != 0) {
                colorReportTemp.setQuestionId(colorReport.getQuestionId());
            }
            stationColorReportTempRepository.save(colorReportTemp);
        }
        return deleteColorReport(auditReport);
    }

    /**
     * 删除基础报告
     */
    private JsonResponse deleteColorReport(AuditReport auditReport) {
        QAuditColorReport qStationColorReport = QAuditColorReport.auditColorReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationColorReport.deleted.eq(false));
        builder.and(qStationColorReport.enabled.eq(true));
        builder.and(qStationColorReport.auditReport.id.eq(auditReport.getId()));
        List<AuditColorReport> colorReportList = (List<AuditColorReport>) auditColorReportRepository.findAll(builder);
        for (AuditColorReport colorReport : colorReportList) {
            auditColorReportRepository.delete(colorReport);
        }
        auditReport.setDeleted(true);
        auditReport.setEnabled(false);
        auditReportRepository.save(auditReport);
        return JsonResponse.successResponse();
    }

    /**
     * 撤回常规报告
     */
    private JsonResponse withdrawServiceReport(User user, StationReport stationReport) {
        logger.info("开始撤回");
        logger.info("创建暂存报告");
        StationReportTemp stationReportTemp = new StationReportTemp();
        stationReportTemp.setReportType(Constants.REPORT_TYPE_UNFINSHED);
        stationReportTemp.setReportCategory(Constants.SERVICE_REPORT);
        stationReportTemp.setUserType(stationReport.getUserType());
        stationReportTemp.setUser(user);
        stationReportTemp.setStation(stationReport.getStation());
        if (stationReport.getStartServiceTime() != null) {
            stationReportTemp.setStartServiceTime(stationReport.getStartServiceTime());
        }
        if (stationReport.getEndServiceTime() != null) {
            stationReportTemp.setEndServiceTime(stationReport.getEndServiceTime());
        }
        if (StringUtils.isNotEmpty(stationReport.getDeparmentIds())) {
            stationReportTemp.setUserIds(stationReport.getDeparmentIds());
        }
        if (StringUtils.isNotEmpty(stationReport.getAnswerOther())) {
            stationReportTemp.setAnswerOther(stationReport.getAnswerOther());
        }
        stationReportUnFinshedRepository.save(stationReportTemp);
        logger.info("创建完毕");
        logger.info("查询原来的常规报告答案");
        QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationRegularServiceReport.deleted.eq(false));
        builder.and(qStationRegularServiceReport.enabled.eq(true));
        builder.and(qStationRegularServiceReport.stationReport.id.eq(stationReport.getId()));

        List<StationRegularServiceReport> regularServiceReportList = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(builder);
        logger.info("赋值到暂存报告答案");
        for (StationRegularServiceReport regularServiceReport : regularServiceReportList) {
            StationRegularServiceReportUnFinshed unFinshed = new StationRegularServiceReportUnFinshed();
            unFinshed.setStationReportTemp(stationReportTemp);
            if (StringUtils.isNotEmpty(regularServiceReport.getAnswerId())) {
                unFinshed.setAnswerId(regularServiceReport.getAnswerId());
            }
            if (StringUtils.isNotEmpty(regularServiceReport.getAnswerOther())) {
                unFinshed.setAnswerOther(regularServiceReport.getAnswerOther());
            }
            if (StringUtils.isNotEmpty(regularServiceReport.getAnswerPhoto())) {
                unFinshed.setAnswerPhoto(regularServiceReport.getAnswerPhoto());
            }
            if (regularServiceReport.getQuestionId() != null && regularServiceReport.getQuestionId() != 0) {
                unFinshed.setQuestionId(regularServiceReport.getQuestionId());
            }
            stationRegularServiceReportUnFinshedRepository.save(unFinshed);
        }
        return deleteServiceReport(stationReport);
    }

    /**
     * 删除常规报告
     */
    private JsonResponse deleteServiceReport(StationReport stationReport) {
        logger.info("开始删除原有报告");
        logger.info("删除常规报告处理记录");
        QServiceReportRecorder qServiceReportRecorder = QServiceReportRecorder.serviceReportRecorder;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qServiceReportRecorder.deleted.eq(false));
        builder.and(qServiceReportRecorder.enabled.eq(true));
        builder.and(qServiceReportRecorder.stationReport.id.eq(stationReport.getId()));
        List<ServiceReportRecorder> reportRecorderList = (List<ServiceReportRecorder>) serviceReportRecorderRepository.findAll(builder);
        for (ServiceReportRecorder recorder : reportRecorderList) {
            serviceReportRecorderRepository.delete(recorder);
        }

        logger.info("删除常规报告历史记录");
        QServiceReportHistoricalRecorder qServiceReportHistoricalRecorder = QServiceReportHistoricalRecorder.serviceReportHistoricalRecorder;
        builder = new BooleanBuilder();
        builder.and(qServiceReportHistoricalRecorder.deleted.eq(false));
        builder.and(qServiceReportHistoricalRecorder.enabled.eq(true));
        builder.and(qServiceReportHistoricalRecorder.stationReport.id.eq(stationReport.getId()));
        List<ServiceReportHistoricalRecorder> reportHistoricalRecorders = (List<ServiceReportHistoricalRecorder>) serviceReportHistoricalRecorderRepository.findAll(builder);
        for (ServiceReportHistoricalRecorder recorder : reportHistoricalRecorders) {
            serviceReportHistoricalRecorderRepository.delete(recorder);
        }

        logger.info("删除常规报告红点");
        QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
        builder = new BooleanBuilder();
        builder.and(qReportRedDot.deleted.eq(false));
        builder.and(qReportRedDot.enabled.eq(true));
        builder.and(qReportRedDot.stationReport.id.eq(stationReport.getId()));
        List<ReportRedDot> reportRedDotList = (List<ReportRedDot>) reportRedDotRepository.findAll(builder);
        for (ReportRedDot redDot : reportRedDotList) {
            reportRedDotRepository.delete(redDot);
        }

        boolean isScore = false;
        logger.info("查询满意度与常规报告关联表");
        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.deleted.eq(false));
//        builder.and(qCustomerRegularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.regularReport.id.eq(stationReport.getId()));
        CustomerRegularReport customerRegularReport = customerRegularReportRepository.findOne(builder);
        logger.info("删除满意度与常规报告关联表");
        if (customerRegularReport != null) {
            customerRegularReportRepository.delete(customerRegularReport);
            if (customerRegularReport.getCustomerReport() != null) {
                isScore = true;
            }
        }

        logger.info("查询常规报告答案");
        QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
        builder = new BooleanBuilder();
        builder.and(qStationRegularServiceReport.deleted.eq(false));
        builder.and(qStationRegularServiceReport.enabled.eq(true));
        builder.and(qStationRegularServiceReport.stationReport.id.eq(stationReport.getId()));
        List<StationRegularServiceReport> regularServiceReportList = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(builder);
        logger.info("删除常规报告原有答案");
        for (StationRegularServiceReport regularServiceReport : regularServiceReportList) {
            stationRegularServiceReportRepository.delete(regularServiceReport);
        }

        logger.info("删除常规报告");
        stationReportRepository.delete(stationReport);
        logger.info("删除成功");
        if (isScore == true) {
            return JsonResponse.successResponseWithData("客户已经填写了满意度报告，此操作会使打分失效，确认撤回/删除此常规报告吗？");
        } else {
            return JsonResponse.successResponse();
        }
    }


}
